﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Configuration;
using FX.CC.Andon.EqKanban.KanbanDataSvcRef;
using System.Windows.Forms;

namespace FX.CC.Andon.EqKanban
{
    public static class _Upgrade {
        public const string version_id_key = "VID";
        public static bool Upgrade(int clientType) {

            string versionIDStr = ConfigurationManager.AppSettings[version_id_key];
            Guid verID = Guid.Empty;
            try{
                verID = new Guid(versionIDStr);
            }
            catch{}

            KanbanDataSvc svc = new KanbanDataSvc();
            try
            {
                var version = svc.GetLatestVersion(clientType);
                if (version.IsExists && verID != version.VersionObj.VersionID)
                {
                    string upgradePath = Application.StartupPath + "\\Upgrade\\";

                    if (!Directory.Exists(upgradePath))
                    {
                        Directory.CreateDirectory(upgradePath);
                    }

                    //发现新版本 启动更新程序
                    var files = svc.GetFiles(version.VersionObj.VersionID);
                    foreach (var file in files)
                    {
                        string fileName = Path.Combine(upgradePath, file.FileName);
                        using (FileStream fs = new FileStream(fileName, FileMode.Create))
                        {
                            fs.Write(file.BIN, 0, file.BIN.Length);
                        }
                    }

                    var cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                    cfg.AppSettings.Settings[version_id_key].Value = version.VersionObj.VersionID.ToString();
                    cfg.Save(ConfigurationSaveMode.Modified); 
                    return true;
                }
                else {
                    return false;
                }
            }
            catch
            {
                //_MsgBox.PopWarning("升级失败");
                return false;
            }
        }
    }
}
